<template>
  <el-upload
    class="upload-demo"
    id="uploadFile"
    :action=url
    ref="upload"
    :limit="1"
    :data="data"
    name="file"
    :on-exceed="handleExceed"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :before-upload="beforeAvatarUpload"
    :on-success="getUploadId"
    :on-error="uploadError"
    :file-list="fileList">
    <el-button size="small" type="warning">上传文件</el-button>
    <span class="uploadTips">{{uploadTip}}</span>
  </el-upload>
</template>

<script>
  import {Message} from 'element-ui';
  import {baseUrl} from "../settings"
  export default {
    props:['format',"data","uploadTip"],
    name: "uploadFile",
    data(){
      return{
        fileList:[],
        url:baseUrl+'file/import',
        loading:null
      }
    },
    methods:{
      //格式限制
      beforeAvatarUpload(file) {
        console.log(file);
        // let fileFormat=file.name.substring(file.name.lastIndexOf(".")+1);
        // let allFormat=["cer","crt"];
        // if(!allFormat.includes(fileFormat)){
        //   Message.warning(`上传文件只能是${allFormat.join(",")}格式`);
        //   return false;
        // }
        this.loading = this.$loading({
                  lock: true,
                  text: '上传中',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.7)'
                });
        // return fileFormat;
      },
      handleRemove(file, fileList) {
          console.log(file, fileList);
      },
      //文件超出个数限制
      handleExceed(files, fileList) {
        this.$message.warning('一次只能上传一个文件');
      },
      //移除前提示
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      //上传成功
      getUploadId(response, file, fileList){
        if(response.code===200){
          this.loading.close();
          Message.success("文件上传成功");
          this.fileList=[];
          this.$emit('getKey',response.result);
        }else{
          Message.error(response.msg);
          this.fileList=[];
          this.loading.close();
        }
      },
      //上传失败
      uploadError(err, file, fileList){
        this.loading.close();
        Message.success("文件上传失败，请重试");
      }
    }
  }
</script>

<style scoped>
  #uploadFile span.uploadTips{
    font-size:12px;
    margin-left:10px;
    color:red;
  }
</style>
